package com.yc154.vote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc154.vote.entity.Items;
import com.yc154.vote.entity.Vote;
import com.yc154.vote.mapper.RecordMapper;
import com.yc154.vote.mapper.VoteMapper;
import com.yc154.vote.service.BizException;
import com.yc154.vote.service.IItemsService;
import com.yc154.vote.service.IVoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiaoYan
 * @since 2025-09-20
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {

    @Autowired
    IItemsService itemsService;
    
    @Autowired
    RecordMapper recordMapper;

    @Transactional
    @Override
    public void create(Vote vote) throws BizException {
        // 同名判断
        LambdaQueryWrapper<Vote> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Vote::getVname, vote.getVname());// vname = ?
        if(exists(lqw)){
            throw new BizException("该投票题目已经添加!", null);
        }
        // 保存主表
        save(vote);
        // 保存从表
        for (Items item : vote.getItems()) {
            // vote.id 是主键,数据库自动生成, mybatis在新增后自动返回
            item.setVid(vote.getId());
            itemsService.save(item);
        }
    }
    
    @Override
    public List<Map<String, Object>> getVoteResults(Integer vid) {
        return recordMapper.getVoteResults(vid);
    }
    
    @Override
    public Integer getTotalVotes(Integer vid) {
        Integer totalVotes = recordMapper.getTotalVotes(vid);
        return totalVotes != null ? totalVotes : 0;
    }
}
